package com.xls.commonlibrary.ad.adn.gm;

import static com.xls.commonlibrary.constant.Const.AD_LAST_TIMESTAMP_BP;
import static com.xls.commonlibrary.constant.Const.AD_LAST_TIMESTAMP_JL;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BP_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BP_TEST_INDEX;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_QP_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_QP_TEST_INDEX;

import android.util.Log;
import android.webkit.ValueCallback;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.orhanobut.logger.Logger;
import com.xls.commonlibrary.http.biz.AdControlUtil;
import com.xls.commonlibrary.http.biz.CodeRewardUtil;
import com.xls.commonlibrary.util.dislogx.DialogXUtil;

import io.reactivex.rxjava3.annotations.NonNull;

// 新插屏广告   注意 旧的id失效不能用了
// todo 水平显示的，没有垂直的问题
public class GMFullUtil {

    String mMediaId = "";
    String mMediaIdHalf = ""; // 融合广告位 正式id  半屏
    String mMediaIdFull = ""; // 融合广告位 正式id  全屏


    private String TAG = "GMUtil";

    private static volatile GMFullUtil singleton = null;
    private boolean isHalf;

    private GMFullUtil() {
    }

    public static GMFullUtil getInstance() {
        if (singleton == null) {
            synchronized (GMFullUtil.class) {
                if (singleton == null) {
                    singleton = new GMFullUtil();
                }
            }
        }
        return singleton;
    }


    private TTFullScreenVideoAd mTTFullScreenVideoAd; // 插全屏广告对象
    private TTAdNative.FullScreenVideoAdListener mFullScreenVideoListener; // 广告加载监听器
    private TTFullScreenVideoAd.FullScreenVideoAdInteractionListener mFullScreenVideoAdInteractionListener; // 广告展示监听器

    AppCompatActivity activity;
    ValueCallback<Boolean> valueCallback;

    public void showAd(@NonNull AppCompatActivity activity,
                       @NonNull boolean isHalf,// 是否半屏
                       @NonNull ValueCallback<Boolean> valueCallback
    ) {


        this.activity = activity;
        this.isHalf = isHalf;
        this.valueCallback = valueCallback;



        if (isHalf) {

            // 间隔时间控制
            if (!AdControlUtil.getInstance().isAble2Show(AD_LAST_TIMESTAMP_BP)) {
                return;
            }
            AdControlUtil.getInstance().saveStartTime(AD_LAST_TIMESTAMP_BP);


//            this.mMediaId = this.mMediaIdHalf;
            this.mMediaId = CodeRewardUtil.getInstance().getAdId(HYLC_XXL_BP_TEST, HYLC_XXL_BP_TEST_INDEX);
        } else {
//            this.mMediaId = this.mMediaIdFull;
            this.mMediaId = CodeRewardUtil.getInstance().getAdId(HYLC_XXL_QP_TEST, HYLC_XXL_QP_TEST_INDEX);
        }


        addLifecycle();
        initListeners();


        loadInterstitialFullAd();

    }

    private void callbackSuccess() {
        if (isHalf){
            AdControlUtil.getInstance().clearStartTime(AD_LAST_TIMESTAMP_BP);
        }

        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(true);
    }

    private void callbackFail() {
        if (isHalf){
            AdControlUtil.getInstance().clearStartTime(AD_LAST_TIMESTAMP_BP);
        }

        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(false);
    }


    private void addLifecycle() {// 重要
        if (this.activity == null) return;

        this.activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            // 还有很多生命周期都可以感知
            // 这里只关注 onDestroy()的注销ad对象
            @Override
            public void onDestroy(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);
//                Logger.d("===========LifecycleOwner=========onDestroy===========");

                /** 6、在onDestroy中销毁广告 */
                if (mTTFullScreenVideoAd != null && mTTFullScreenVideoAd.getMediationManager() != null) {
                    mTTFullScreenVideoAd.getMediationManager().destroy();
                }

            }
        });
    }

    private void loadInterstitialFullAd() {
        /** 1、创建AdSlot对象 */
        AdSlot adslot = new AdSlot.Builder()
                .setCodeId(this.mMediaId)
                .setOrientation(TTAdConstant.ORIENTATION_VERTICAL)
                .build();

        /** 2、创建TTAdNative对象 */
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(this.activity);

        /** 3、创建加载、展示监听器 */
        initListeners();

        /** 4、加载广告 */
        adNativeLoader.loadFullScreenVideoAd(adslot, this.mFullScreenVideoListener);
    }

    // 在加载成功后展示广告
    private void showInterstitialFullAd() {
        if (this.mTTFullScreenVideoAd == null) {
            Log.d(TAG, "请先加载广告或等待广告加载完毕后再调用show方法");
            return;
        }
        /** 5、设置展示监听器，展示广告 */
        this.mTTFullScreenVideoAd.setFullScreenVideoAdInteractionListener(this.mFullScreenVideoAdInteractionListener);
        this.mTTFullScreenVideoAd.showFullScreenVideoAd(this.activity);
    }

    private void initListeners() {
        // 广告加载监听器
        this.mFullScreenVideoListener = new TTAdNative.FullScreenVideoAdListener() {
            public void onError(int code, String message) {
//                DialogXUtil.closeLoading();

                Log.d(TAG, "InterstitialFull onError code = " + code + " msg = " + message);
                callbackFail();
            }

            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                Logger.d("=======插全屏=====广告加载成功========");

//                callbackSuccess();

                mTTFullScreenVideoAd = ad;
            }

            public void onFullScreenVideoCached() {
                Logger.d("=======插全屏=====广告视频本地加载完成的回调，即将废弃========");
            }

            public void onFullScreenVideoCached(TTFullScreenVideoAd ad) {
                Logger.d("=======插全屏=====广告视频本地加载完成的回调========");
                mTTFullScreenVideoAd = ad;

//                DialogXUtil.closeLoading();
                showInterstitialFullAd();
            }
        };
        // 广告展示监听器
        this.mFullScreenVideoAdInteractionListener = new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
            public void onAdShow() {
                Log.d(TAG, "InterstitialFull onAdShow");
            }

            public void onAdVideoBarClick() {
                Log.d(TAG, "InterstitialFull onAdVideoBarClick");
            }

            public void onAdClose() {
                Log.d(TAG, "InterstitialFull onAdClose");

                callbackSuccess();

            }

            public void onVideoComplete() {
                Log.d(TAG, "InterstitialFull onVideoComplete");


            }

            public void onSkippedVideo() {
                Log.d(TAG, "InterstitialFull onSkippedVideo");

//                callbackFail();
            }
        };
    }


}
